package com.ogawa.joypal.user.viewmodel

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.OnLifecycleEvent
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.LogUtils
import com.ogawa.base.base.BaseViewModel
import com.ogawa.base.bean.LoadState
import com.ogawa.base.constants.Constants.Companion.NET_DEF_PLATFORM
import com.ogawa.projectcommon.utils.dataConvert
import com.ogawa.projectcommon.utils.launch
import com.ogawa.projectcommon.network.RetrofitManager
import com.ogawa.joypal.user.bean.UserLoginRequest
import com.ogawa.joypal.user.bean.UsercaptchaBean
import com.ogawa.joypal.user.bean.UserloginBean
import com.ogawa.joypal.user.service.UserApiService
import com.ogawa.projectcommon.datacollect.DataCollectUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class LoginViewModel : BaseViewModel() {
    var getSmsCountNumber = MutableLiveData<Int>()
    val mUsercaptchBean = MutableLiveData<UsercaptchaBean>()
    val mLoginBean = MutableLiveData<UserloginBean>()

    init {
        getSmsCountNumber.value = 0
    }

    fun userLogin(mobile: String, sms: String) {
        launch({
            loadState.value = LoadState.Loading("")
            var request = UserLoginRequest().apply {
                userName = mobile
                captcha = sms
                loginType = "quickLogin"
            }
            mLoginBean.value = RetrofitManager.INSTANCE.createService(UserApiService::class.java)
                .userLogin(request)
                .dataConvert()
            DataCollectUtils.loginEvent("mobile", mLoginBean.value?.user?.userName, mobile)
            loadState.value = LoadState.Success("")
        }, { loadState.value = LoadState.Fail(it.message ?: "") }, {})
    }


    fun getLoginBean(mobile: String) {
        launch({
            loadState.value = LoadState.Loading("")
            mUsercaptchBean.value =
                RetrofitManager.INSTANCE.createService(UserApiService::class.java)
                    .smsLogin("86", mobile, NET_DEF_PLATFORM, "login")
                    .dataConvert()
            loadState.value = LoadState.Success("")
            getSmsCountNumber.value = 60

            while (getSmsCountNumber.value!! > 0) {
                viewModelScope.launch(Dispatchers.Main) {
                    getSmsCountNumber.value = getSmsCountNumber.value!! - 1
                }
//                LogUtils.e("倒计时 ${getSmsCountNumber.value}")
                withContext(Dispatchers.IO) {
                    Thread.sleep(1000)
                }
            }
        }, { loadState.value = LoadState.Fail(it.message ?: "") }, {})
    }


    //不需要，在ViewModel销毁时候会自己清除
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    open fun onDestroy() {
        LogUtils.e("onDestroy")
        viewModelScope.cancel()
    }


}
